<?php
namespace Client\Controller;

use Zend\View\Model\ViewModel;
use Client\Model\Order;
use Zend\Db\Sql\Expression;
use Client\Common\LoggerHelper;
use Client\Exception\ClientException;
use Client\Common\UploaderHelper;

class MyOrderController extends InitializeController
{   
    public function indexAction(){
        
        $list = $this->getOrderTable()->getOrderList(array('user_id'=>$this->user_id));
        $order_list = array();
        foreach ($list as $order) {
            $order['item_list'] = $this->getOrderitemTable()->getList(array('order_id'=>$order['order_id']));     
            Order::filter($order);
            array_push($order_list,$order);          
        }
               
        $data = array(
          'list' => $order_list 
        );
        return new ViewModel($data);
    }
    
    public function scoreAction(){
        $id = $this->params()->fromRoute('id', 0);
         
        $order = $this->getOrderTable()->getByOrderNo($id);
        $orderitems = $this->getOrderitemTable()->getList(array('order_id'=>$order['order_id']));
        
        $org = $this->getOrganizationTable()->getById($order['org_id']);
        
        return new ViewModel(array(
            'order' => $order,
            'org'=> $org,
            'orderitems' => $orderitems,
        ));
    }
    
    /*
     *
     */
    public function cancelAction() {
        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id', 0);
    
        $user = $this->getUserTable()->getById($this->user_id);
        if(empty($user)) {
            throw new \Exception("买家不存在");
        }
    
        $db = $this->getAdapter()->getDriver()->getConnection();
        $db->beginTransaction();
        try
        {
            //订单信息
            $order = $this->getOrderTable()->getByOrderNo($id);
            if(empty($order)) {
                throw new \Exception("订单不存在");
            }
             
            if ($order['status'] == 1) {
                $set = array(
                    'status' => 4
                );
                $this->getOrderTable()->update($set, array('order_id'=>$order['order_id']));
            } elseif($order['status']== 2) {
                $set = array(
                    'cancel_apply' => 1
                );
                $this->getOrderTable()->update($set, array('order_id'=>$order['order_id']));
            }
            $db->commit();
            return $this->redirect()->toRoute('myorder', array(
                'action' => 'index'
            ));
        }
        catch(\Exception $e)
        {
            $db->rollBack();
            LoggerHelper::client_exception($e);
            throw new ClientException('3001');
        }
    }
    
    public function orderDetailAction(){
        $id = $this->params()->fromRoute('id', 0);
         
        $order = $this->getOrderTable()->getByOrderNo($id);
    
        $org = $this->getOrganizationTable()->getById($order['org_id']);
    
        $userInfo = $this->getUserTable()->getUserInfo($this->user_id);
    
        $orderitems = $this->getOrderitemTable()->getFoodList(array('order_id'=>$order['order_id']));
        $items = array();
        foreach ($orderitems as $item) {
            if (!empty($item['oi_meal_send_time']) && empty($items[$item['oi_meal_send_time']])) {
                $items[$item['oi_meal_send_time']] = array();
            }
            if (empty($items[$item['oi_meal_send_time']][$item['oi_meal_type']])) {
                $items[$item['oi_meal_send_time']][$item['oi_meal_type']] = array();
            }
            if ($items[$item['oi_meal_send_time']][$item['oi_meal_type']]!== null) {
                array_push($items[$item['oi_meal_send_time']][$item['oi_meal_type']], $item);
            }
        }

        $view = new ViewModel(array(
            'order' => $order,
            'org'=> $org,
            'orderitems' => $items,
            'userInfo' => $userInfo
        ));

        $view->setTemplate('client/my-order/order-detail.phtml'); // path to phtml file under view folder
        return $view;
    }
    
    public function orderDetailMallAction(){
        $id = $this->params()->fromRoute('id', 0);
         
        $order = $this->getOrderTable()->getByOrderNo($id);
      
        $org = $this->getOrganizationTable()->getById($order['org_id']);
        
        $userInfo = $this->getUserTable()->getUserInfo($this->user_id);
                 
        $orderitems = $this->getOrderitemTable()->getList(array('order_id'=>$order['order_id']));
        $view = new ViewModel(array(
            'order' => $order,
            'org'=> $org,
            'orderitems' => $orderitems,
            'userInfo' => $userInfo
        ));
        $view->setTemplate('client/my-order/order-detail-mall.phtml'); // path to phtml file under view folder
        return $view;
    }
    
    public function afterSalesAction(){
        
        $id = $this->params()->fromRoute('id', 0);
        $order = $this->getOrderTable()->getByOrderNo($id);
        Order::filter($order);
        $orderitems = $this->getOrderitemTable()->getList(array('order_id'=>$order['order_id']));
        $data = array(
            'order' => $order,
            'orderitems' => $orderitems,
        );
        return new ViewModel($data);
    }
    
    public function afterSalesSaveAction(){
    
        $data = $this->request->getPost()->toArray();
        $order_no = $data['order_no'];
        $mark = $data['mark'];        
        $orderTable=$this->getOrderTable();
        $orderTable->beginTransaction();
        try{
            $order = $this->getOrderTable()->getByOrderNo($order_no);
            $orderitems = $this->getOrderitemTable()->getList(array('order_id'=>$order['order_id']));
            for($i=0;$i<count($orderitems);$i++){
                $itemId    = $data['item_id_'.$i];
                $itemAmount = $data['item_num_'.$i];
                
                if (!empty($itemId)) {
                    $orderitem = $this->getOrderitemTable()->getById($itemId);
                    if (empty($orderitem)) {
                        throw new ClientException('3004');                        
                    }
                    
                    $set = array(
                        'oi_id' => $orderitem['oi_id'], 
                        'return_amount' => $itemAmount,    
                        'order_id' => $order['order_id']
                    );
                    $this->getReturnOrderitemTable()->insert($set);
                }
            }
            
            $pic_list = array();
            
            for($i = 1 ; $i<=4;$i++) {
                if($_FILES['picFile_'.$i]['error']==0){
                    $fileInfo = $this->uploadImg('picFile_'.$i);
                    if ($fileInfo['state']==='SUCCESS') {
                        $pic_list[$i] = $fileInfo['url'];
                    }else{                   
                        throw new ClientException('3005');
                    }
                }
            }
            $set = array(
                'order_id' => $order['order_id'],
                'mark' => $mark,
                'pic_1' => empty($pic_list[1])?"":$pic_list[1],
                'pic_2' => empty($pic_list[2])?"":$pic_list[2],
                'pic_3' => empty($pic_list[3])?"":$pic_list[3],
                'pic_4' => empty($pic_list[4])?"":$pic_list[4],
                'create_time' => new Expression("NOW()"),
                'status' => 1,
            );
            $this->getReturnOrderTable()->insert($set);
            
            $orderTable->commit();
            return $this->redirect()->toRoute('myorder');
        }    
        catch(\Exception $e)
        {
            $orderTable->rollBack();
            LoggerHelper::client_exception($e);
            throw new ClientException('6001');
        }
        
        die();
    }

    public function scoreSaveAction(){
        $post = $this->request->getPost();       
        
        $order = $this->getOrderTable()->getByOrderNo($post['order_no']);
        
        $set = array(
            'order_id' => $order->order_id,
            'create_time' => new Expression('NOW()'),
            'clear_score' => $post['clear_score'],
            'taste_score' => $post['taste_score'],
            'speed_score' => $post['speed_score'],
            'service_score' => $post['service_score'],
            'total_score' => $post['total_score'],
            'has_score' => 1
        );
        $this->getOrderScoreTable()->insert($set);
    
        return $this->redirect()->toRoute('myorder'); 
    }
    
    /**
     * 上传图片
     * @param unknown $fileName 控件名称
     */
    protected function uploadImg($fileName)
    {
        $uploaderHelper = new UploaderHelper($fileName,$this->getUploadConfig());
        $fileInfo = $uploaderHelper->getFileInfo();
        if($fileInfo['state']==='SUCCESS') $fileInfo['url'] = $fileInfo['url'];
        return $fileInfo;
    }
    protected function getUploadConfig()
    {
        $pathFormat = UploaderHelper::getPathFormat("/image/{yyyy}{mm}/{time}{rand:6}");
        $config = array(
            "pathFormat" => $pathFormat,
            "maxSize" => 2048000,
            "allowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
        );
        return $config;
    }
}